//------------------------------------------------------------------------------
// Fichiers d'ent�te utilis�s
//------------------------------------------------------------------------------
#include "LocalThresholdOperator.hpp"
#include "Tools/Logger.hpp"

//------------------------------------------------------------------------------
// Définition de constantes
//------------------------------------------------------------------------------

namespace ImageAnalysis
{

	//----------------------------------------------------------------------
	// Constructeur
	//----------------------------------------------------------------------
	LocalThresholdOperator::LocalThresholdOperator( Gradiant* gradiant, BinaryImage* image, ThresholdFinder* finder, int windowSize ):
	Operator(),
	thresholdFinder(finder),
	currentGradiant(gradiant),
	currentThresholdImage(image),
	thresholdWindowSize(windowSize)
	{	
	
	}

	//----------------------------------------------------------------------
	// Destructeur
	//----------------------------------------------------------------------
	LocalThresholdOperator::~LocalThresholdOperator( )
	{
	
	}

	//----------------------------------------------------------------------
	// La fenetre doit être impaire
	//----------------------------------------------------------------------
	void LocalThresholdOperator::Process( )
	{
		// Récupération de la taille de l'image à seuiller ainsi que la valeur du seuil		
		unsigned char* threshold;
		unsigned char value;		
		int pixelIndex;
		int offset;
		
		// Seuillage de tous les pixels de l'image
		offset = (thresholdWindowSize-1)/2;		
		for( int j=offset; j < currentGradiant->GetHeight()-offset; ++j )
		{
			for( int i=offset; i < currentGradiant->GetWidth()-offset; ++i )
			{			
				pixelIndex = i+j*currentGradiant->GetWidth();
				
				// Récupération du seuil local 
				Region currentRegion(i-offset,j-offset,thresholdWindowSize,thresholdWindowSize);
				
				// Récupération du seuil local 
				threshold = thresholdFinder->GetOneThreshold( &currentRegion, currentGradiant );
	
				// Seuillage du pixel courant
				value = (currentGradiant->GetGradiantNorm( pixelIndex ) >= threshold[0])?BinaryImage::WHITE_VALUE:BinaryImage::BLACK_VALUE;				
				currentThresholdImage->SetPixel(pixelIndex,&value);

				delete[] threshold;
			}
		}	
		
	}
}


